<?php

namespace app\webapi\common;

use library\OWException;
use think\facade\Request;
use think\Validate;

class BaseValidate extends Validate
{
    /**
     * 场景校验
     */
    public function goCheck($scene)
    {
        $params = Request::param();
        $result = $this->scene($scene)->check($params);
        if ($result !== true) {
            throw new OWException($this->getError(), '', 400);
        }
        return $params;
    }

    /**
     * @desc 排序json格式校验
     * @param $json
     * @return mixed
     */
    function check_sort_json_array($json, $args)
    {
        $json_array = json_decode($json, true);
        if (!$json_array) {
            throw new OWException('参数格式错误');
        }
        if (!is_array($args)) {
            throw new OWException('服务器错误');
        }

        $allow_args_keys = array_keys($args);
        foreach ($json_array as $key => $v) {
            $temp_keys = array_keys($v);
            foreach ($temp_keys as $item) {
                if (!in_array($item, $allow_args_keys)) {
                    throw new OWException('json对象key值只允许id,sort');
                }

                switch ($args[$item]) {
                    case 'number':
                        if (!is_numeric($v[$item])) {
                            throw new OWException("${item}必须是整型类型");
                        }
                        break;
                    case 'string':
                        if (!is_string($v[$item])) {
                            throw new OWException("${item}必须是字符串类型");
                        }
                        break;
                    case 'bool':
                        if (!is_bool($v[$item])) {
                            throw new OWException("${item}必须是布尔类型");
                        }
                        break;
                    case 'array':
                        if (!is_array($v[$item])) {
                            throw new OWException("${item}必须是数组类型");
                        }
                        break;
                    default:
                        throw new OWException('参数错误');
                }
            }

        }
        return $json_array;
    }
}